/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author gzero
 */
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdom2.*; 
import org.jdom2.output.*;
import org.jdom2.input.*;

public class gest {
    Vector v = new Vector();
    public void manInstall() throws IOException
    {
        InputStreamReader input = new InputStreamReader(System.in);
        BufferedReader tastiera = new BufferedReader (input);
        
        showList();
        int scelta =-1;
        try{
            scelta=Integer.valueOf(tastiera.readLine()).intValue();
        }catch(Exception e){}
        
        try {
            URL website = new URL( ((link)v.elementAt(scelta)).getLink() );
            ReadableByteChannel rbc = Channels.newChannel(website.openStream());
            String s_file;
            s_file=((link)v.elementAt(scelta)).getSaveFile();
            String nomeFile;
            nomeFile= ((link)v.elementAt(scelta)).getName();
            /*leggere dimensione file*/
            URLConnection conn = website.openConnection();
            int dimFile=conn.getContentLength();
            //-------------------------
            System.out.println("["+ (scelta+1) +"/"+v.size()+"] Download in corso ["+nomeFile+"] Size ["+dimFile+"]");
            FileOutputStream fos = new FileOutputStream(s_file + ".exe");
            fos.getChannel().transferFrom(rbc, 0, 1 << 24);                
            fos.close();
        } catch (MalformedURLException e) {
            Logger.getLogger(gest.class.getName()).log(Level.SEVERE, null, e);
        }
        String nameFile= ((link)v.elementAt(scelta)).getSaveFile()+".exe";
         Runtime.getRuntime().exec("./"+nameFile);
        
    }
    public void showList()
    {
        for(int i=0;i<v.size();i++)
        {
            System.out.println("["+i+"] "+ ((link)v.elementAt(i)).getName());
        }
    }
    public void downloadXML() throws IOException
    {        
            try{
            URL website = new URL("http://download.xzone5.it/list.xml");
            ReadableByteChannel rbc = Channels.newChannel(website.openStream());
            String nomeFile = "Lista Software";
            /*leggere dimensione file*/
            URLConnection conn = website.openConnection();
            int dimFile=conn.getContentLength();
            //-------------------------
            System.out.println("Download in corso ["+nomeFile+"] Size["+dimFile+"]");
            FileOutputStream fos = new FileOutputStream("./list.xml");
            fos.getChannel().transferFrom(rbc,0,1 << 24);
            } catch (MalformedURLException e) {
                Logger.getLogger(gest.class.getName()).log(Level.SEVERE, null, e);
            }
    }
    public void leggiXML()
    {
        link x;
        try{
        SAXBuilder builder = new SAXBuilder(); 
        Document document = builder.build(new File("./list.xml")); 
        Element root = document.getRootElement();
        List children = root.getChildren();
        Iterator iterator = children.iterator();
        String name;
        String link;
        String s_name;
        while(iterator.hasNext()){
            Element item = (Element)iterator.next();
            name = item.getAttributeValue("nome");
            //System.out.println(x.getName());            
            link = item.getAttributeValue("link");
            //System.out.println(x.getLink()); 
            s_name = item.getAttributeValue("save_name");
            //creo oggetto con i valori letti
            x = new link(name,link,s_name);
            //lo aggiungo al vector
            v.addElement(x);
        }
        }catch(Exception e){}
    }    
    public void editXML()
    {/*
        try{
        SAXBuilder builder = new SAXBuilder();
        File xmlFile = new File("foo.xml");
        Document doc = builder.build(xmlFile);
        Element root = doc.getRootElement();

        Element newChild = new Element("NewChild");
        Attribute newAtt = new Attribute(name,link);
        newChild.setAttribute(newAtt);
        root.addContent(newChild);
        XMLOutputter outputter = new XMLOutputter();
        outputter.output(document, new FileOutputStream("foo.xml"));
        }catch(Exception e){}*/
    }    
    public void downloadFiles() throws IOException
    {
        System.out.println("---- Inizio Download ----");
        for(int i=0;i<v.size();i++)
        {            
            try {
                URL website = new URL( ((link)v.elementAt(i)).getLink() );
                ReadableByteChannel rbc = Channels.newChannel(website.openStream());
                String s_file;
                s_file=((link)v.elementAt(i)).getSaveFile();
                String nomeFile;
                nomeFile= ((link)v.elementAt(i)).getName();
                /*leggere dimensione file*/
                URLConnection conn = website.openConnection();
                int dimFile=conn.getContentLength();
                //-------------------------
                System.out.println("["+ (i+1) +"/"+v.size()+"] Download in corso ["+nomeFile+"] Size ["+dimFile+"]");
                FileOutputStream fos = new FileOutputStream(s_file + ".exe");
                fos.getChannel().transferFrom(rbc, 0, 1 << 24);                
                fos.close();
            } catch (MalformedURLException e) {
                Logger.getLogger(gest.class.getName()).log(Level.SEVERE, null, e);
            }
        }
        System.out.println("---- Fine Download ----");
    }
    public void startInstall() throws InterruptedException
    {
        String[] nameFile = new String [v.size()];
        for(int i=0;i<v.size();i++){
               nameFile[i] = ((link)v.elementAt(i)).getSaveFile()+".exe";
        }
        for(int i=0;i<v.size();i++){
            System.out.println("installazione ["+(i+1)+"/"+v.size()+"] :"+nameFile[i]);
            try{    
                while(true){           
                    if(i!=0){//per tutta la lista tranne il primo prog
                        if(!isRunning(nameFile[i-1])){
                            System.out.println("Esecuzione:"+nameFile[i]);
                            Runtime.getRuntime().exec("./"+nameFile[i]);
                            break;
                        }else
                            //pausa in millisecondi 1/1000
                            Thread.sleep(5000);
                    }else//solo nel primo programma
                    {
                        System.out.println("Esecuzione:"+nameFile[i]);
                        Runtime.getRuntime().exec("./"+nameFile[i]);
                        break;
                    }
                }
            }
            catch(IOException io){
                    System.out.println(io.getMessage()) ;
            }
        }
    }
    public Iterator getProc () 
    {
		List lista=new ArrayList();
		StringBuffer sb=new StringBuffer();
		try {
			Process tasklist=Runtime.getRuntime().exec("tasklist");
			BufferedInputStream out=new BufferedInputStream(tasklist.getInputStream());
			byte[] buffer=new byte[1000];
			int numbytes;
			while((numbytes=out.read(buffer)) != -1 ) {
    				sb.append(new String(buffer, 0, numbytes));
			}
		}
		catch (IOException ioe) {
			System.out.println("IOException: impossibile accedere alla lista dei processi");
		}
		String[] rows=sb.toString().split("\\n");
		for (int i=3; i<rows.length; i++) {
			lista.add(rows[i].substring(0, 25));
		}

		Iterator iter=lista.iterator();
                        return iter;
		}   
    public boolean isRunning(String proc)
    {
        Iterator list = getProc();
        
        while(list.hasNext())
        {
            if(list.next().toString().indexOf(proc)!=-1)
                return true;
        }
        return false;
    }
    public int showMenu()
    {
        InputStreamReader input = new InputStreamReader(System.in);
        BufferedReader tastiera = new BufferedReader (input);
        
        System.out.println("---- MENU ----");
        System.out.println("1 - Seleziona manualmente programmi da installare");
        System.out.println("2 - Installa tutti i programmi");
        System.out.println("3 - vedi lista programmi");
        int scelta=-1;
        try{
            scelta = Integer.valueOf(tastiera.readLine()).intValue();
        }catch(Exception e){}
        
        return scelta;
    }
}